package com.example.app_emu.core

import android.content.Context
import android.net.wifi.WifiManager
import android.util.Log
import com.example.app_emu.core.Emulator
import com.example.app_emu.device.MyEmulatorDevice
import com.example.lib_core.task.Task
import com.example.session.EndPoint
import java.net.Inet4Address

object EmulatorManage {

    const val DEFAULT_EMULATOR_PORT = 7700

    val emulator = Emulator() //service

    init {
        val myEmulator = MyEmulatorDevice(emulator, EmulatorDevice.Profile())
        myEmulator.profile.name = "模拟器设备"
        myEmulator.profile.sn = "9527"
        myEmulator.profile.address = EndPoint("10.0.0.0")
        myEmulator.powerOn()
        emulator.registerDevice(myEmulator)
    }

    fun startEmulator(context: Context) {
        Task.singleTask {
            //获取wifi服务
            val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
            //判断wifi是否开启
            if (!wifiManager.isWifiEnabled) throw RuntimeException("no Wifi")
            val wifiInfo = wifiManager.connectionInfo
            val ipAddress = wifiInfo.ipAddress

            val localIpString = (ipAddress and 0xFF).toString() +
                    "." + (ipAddress shr 8 and 0xFF) +
                    "." + (ipAddress shr 16 and 0xFF) +
                    "." + (ipAddress shr 24 and 0xFF)

            val localIp = Inet4Address.getByName(localIpString)

            val option = EmulatorDebugLink.Option()
            option.emulatorAddress = localIp
            option.emulatorPort = DEFAULT_EMULATOR_PORT
            Log.e("xiao","localIp$localIp")

            val devices = emulator.getDevice()
            for (device in devices){
                device.profile.ip = localIp
            }

            emulator.stop()
            emulator.start(option)

        }.success {
            println("emulator start ok")
        }.error {
            it.printStackTrace()
        }.start()
    }

    fun stopEmulator() {
        Task.singleTask {
            emulator.stop()
        }.success {
            println("emulator stop ok")
        }.error {
            it.printStackTrace()
        }.start()
    }
}